package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;
    public static String DetailUrl = "http://8.137.19.140:9090/blog_detail.html?blogId=163990";
    public WebDriverWait wait = null;

    public Utils(String url)
    {
        //调用driver对象
        driver = createDriver();
        wait = new WebDriverWait(driver,Duration.ofSeconds(2));
        driver.get(url);
    }

    /**
     * 获取驱动对象
     * @return
     */
    public static WebDriver createDriver()
    {
        if(driver == null)
        {
            //下载驱动
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //允许访问所有的链接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    /**
     * 屏幕截图
     * @throws IOException
     */
    public void screenShot() throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirName = sim1.format(System.currentTimeMillis());
        String fileName = sim2.format(System.currentTimeMillis());
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String filePath = "./src/test/java/images/"+dirName+"/"+fileName+".png";
        FileUtils.copyFile(screenshot,new File(filePath));
    }
}
